<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */ 
namespace Home\Controller;


use \PayPal\Api\Payer;
use \PayPal\Api\Item;
use \PayPal\Api\ItemList;
use \PayPal\Api\Details;
use \PayPal\Api\Amount;
use \PayPal\Api\Transaction;
use \PayPal\Api\RedirectUrls;
use \PayPal\Api\Payment;
use \PayPal\Exception\PayPalConnectionException;
use PayPal\Api\PaymentExecution;
class PaymentController extends BaseController {
    
    public $payment; //  具体的支付类
    public $pay_code; //  具体的支付code
 
    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();

        // tpshop 订单支付提交
        $pay_radio = $_REQUEST['pay_radio'];
        if(!empty($pay_radio))
        {                         
            $pay_radio = parse_url_param($pay_radio);

            $this->pay_code = $pay_radio['pay_code']; // 支付 code
        }
        else // 第三方 支付商返回
        {

            $_GET = I('get.');            
            //file_put_contents('./a.html',$_GET,FILE_APPEND);    
            $this->pay_code = I('get.pay_code');
            unset($_GET['pay_code']); // 用完之后删除, 以免进入签名判断里面去 导致错误
        }                        
        //获取通知的数据
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];


//        if($this->pay_code=='paypal'){
//
//            //paypal 支付配置
//
//
//        }else{
//
//        }

        // 导入具体的支付类文件
        include_once  "plugins/payment/{$this->pay_code}/{$this->pay_code}.class.php"; // D:\wamp\www\svn_tpshop\www\plugins\payment\alipay\alipayPayment.class.php
        $code = '\\'.$this->pay_code; // \alipay
        $this->payment = new $code();


    }
   
    /**
     * tpshop 提交支付方式
     */
    public function getCode(){






            C('TOKEN_ON',false); // 关闭 TOKEN_ON
            header("Content-type:text/html;charset=utf-8");            
            $order_id = I('order_id'); // 订单id
            // 修改订单的支付方式
            $payment_arr = M('Plugin')->where("`type` = 'payment'")->getField("code,name");
            M('order')->where("order_id = $order_id")->save(array('pay_code'=>$this->pay_code,'pay_name'=>$payment_arr[$this->pay_code]));
            
            $order = M('order')->where("order_id = $order_id")->find();
            if($order['pay_status'] == 1){
            	$this->error('This order has been paid');
            }            
            // tpshop 订单支付提交
            $pay_radio = $_REQUEST['pay_radio'];
            $config_value = parse_url_param($pay_radio); // 类似于 pay_code=alipay&bank_code=CCB-DEBIT 参数
                if($this->pay_code == 'paypal'){

                    require "vendor/autoload.php"; //载入sdk的自动加载文件
                    define('SITE_URL', 'http://www.wawa.com'); //网站url自行定义  如果是本地是 localhost/后面的看你自己的代码位置pay.php的位置 写到文件夹的位置就可以
                     //创建支付对象实例

//                    $cliend_id ='AQJWlHuCnfKl_VlTv-J_jO9VV5LMGukYGxwv_6awhTbzILCv2Hl8U8vHef5wfMTyQPH103yXnUSxH3fM';
//                    $secret='EHq5ZSGWb51jOtvz_W5a9vnueWrFf_U86WOuiSJGLwmhHYMTWC2i0LE-tx8I52uL7yQfvqrqVobtu1hZ';

//                    $cliend_id='';
//                    $secret='';



                    $cliend_id='AaVZC0rg_3h1N5tSm1NlwVaSr7Jhak30SHYEkTqCwoFALYBqHk_OpJJc1nxnq_6jITnP5PEfIPAKd4dM';
                    $secret='EMMrl0W_WMoWTJxVYydg3u3CJiwW0k7WCHy-HETGGe2109QLWVSqduiInrobwibCgqXHLfrJuAj8T92W';

                    $paypal = new \PayPal\Rest\ApiContext(
                        new \PayPal\Auth\OAuthTokenCredential($cliend_id,$secret)
                    );

                    $product = 'test_pay';
                    $price = 0.01;
                    $shipping = 0.01; //运费

                    $total =$price+$shipping;

                    $payer = new Payer();
                    $payer->setPaymentMethod('paypal');

                    $item = new Item();
                    $item->setName($product)
                        ->setCurrency('USD')
                        ->setQuantity(1)
                        ->setPrice($price);

                    $itemList = new ItemList();
                    $itemList->setItems([$item]);

                    $details = new Details();
                    $details->setShipping($shipping)
                        ->setSubtotal($price);

                    $amount = new Amount();
                    $amount->setCurrency('USD')
                        ->setTotal($total)
                        ->setDetails($details);

                    $transaction = new Transaction();
                    $transaction->setAmount($amount)
                        ->setItemList($itemList)
                        ->setDescription("支付描述内容")
                        ->setInvoiceNumber(uniqid());

                    $redirectUrls = new RedirectUrls();
//                    $redirectUrls->setReturnUrl(SITE_URL . '/pay.php?success=true')
                    $redirectUrls->setReturnUrl(SITE_URL . '/index.php?m=Home&c=cart&a=pay&success=true')
//                    $redirectUrls->setReturnUrl(SITE_URL . 'index.php?m=Home&c=Payment&a=pay/success/true')
                        ->setCancelUrl(SITE_URL . '/index.php?m=Home&c=Cart&a=pay&success=false');
//                        ->setCancelUrl(SITE_URL . '/Home/Payment/pay/success/false');
                    $payment = new Payment();
                    $payment->setIntent('sale')
                        ->setPayer($payer)
                        ->setRedirectUrls($redirectUrls)
                        ->setTransactions([$transaction]);

                    try {
                        $payment->create($paypal);
                    } catch (PayPalConnectionException $e) {
                        echo $e->getData();
                        die();
                    }

                    $approvalUrl = $payment->getApprovalLink();
//                    exit(json_encode($approvalUrl));
                    print_r($approvalUrl);exit;

//                  $res =  $this->payment->get_code($order_id);
//
//                  exit(json_encode($res));


//        exit($res);
//                  dump($res);exit;
//                    return $res;
//                  return json_decode($res);


                }

            $code_str = $this->payment->get_code($order,$config_value);
            //微信JS支付
           if($this->pay_code == 'weixin' && $_SESSION['openid'] && strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
               $code_str = $this->payment->getJSAPI($order,$config_value);
               exit($code_str);
           }


           $this->assign('code_str', $code_str); 
           $this->assign('order_id', $order_id); 
           $this->display('payment');  // 分跳转 和不 跳转 
    }



    public function pay(){
        $cliend_id='AaVZC0rg_3h1N5tSm1NlwVaSr7Jhak30SHYEkTqCwoFALYBqHk_OpJJc1nxnq_6jITnP5PEfIPAKd4dM';
        $secret='EMMrl0W_WMoWTJxVYydg3u3CJiwW0k7WCHy-HETGGe2109QLWVSqduiInrobwibCgqXHLfrJuAj8T92W';
        $paypal = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential($cliend_id,$secret)
        );



        if(!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])){
            die();
        }

        if((bool)$_GET['success']=== 'false'){

            echo 'Transaction cancelled!';
            die();
        }

        $paymentID = $_GET['paymentId'];
        $payerId = $_GET['PayerID'];

        $payment = Payment::get($paymentID, $paypal);

        $execute = new PaymentExecution();
        $execute->setPayerId($payerId);

        try{
            $result = $payment->execute($execute, $paypal);
        }catch(Exception $e){
            die($e);
        }
        echo '支付成功！感谢支持!';

    }

    public function getPay(){
    	C('TOKEN_ON',false); // 关闭 TOKEN_ON
    	header("Content-type:text/html;charset=utf-8"); 
    	$order_id = I('order_id'); // 订单id
    	// 修改充值订单的支付方式
    	$payment_arr = M('Plugin')->where("`type` = 'payment'")->getField("code,name");
    	
    	M('recharge')->where("order_id = $order_id")->save(array('pay_code'=>$this->pay_code,'pay_name'=>$payment_arr[$this->pay_code]));    
    	$order = M('recharge')->where("order_id = $order_id")->find();
    	if($order['pay_status'] == 1){
    		$this->error('This order has been paid');
    	}
    	$pay_radio = $_REQUEST['pay_radio'];
    	$config_value = parse_url_param($pay_radio); // 类似于 pay_code=alipay&bank_code=CCB-DEBIT 参数
        $order['order_amount'] = $order['account'];
    	$code_str = $this->payment->get_code($order,$config_value);
    	//微信JS支付
    	if($this->pay_code == 'weixin' && $_SESSION['openid'] && strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
    		$code_str = $this->payment->getJSAPI($order,$config_value);
    		exit($code_str);
    	}
    	$this->assign('code_str', $code_str);
    	$this->assign('order_id', $order_id);
    	$this->display('recharge'); //分跳转 和不 跳转
    }
    
    // 服务器点对点 // http://www.tp-shop.cn/index.php/Home/Payment/notifyUrl        
    public function notifyUrl(){            
        $this->payment->response();            
        exit();
    }

    // 页面跳转 // http://www.tp-shop.cn/index.php/Home/Payment/returnUrl        
    public function returnUrl(){
        $result = $this->payment->respond2(); // $result['order_sn'] = '201512241425288593';
        
        if(stripos($result['order_sn'],'recharge') !== false)
        {
            $order = M('recharge')->where("order_sn = '{$result['order_sn']}'")->find();
            $this->assign('order', $order);
            if($result['status'] == 1)
                $this->display('recharge_success');   
            else
                $this->display('recharge_error');   
            exit();            
        }
                
        $order = M('order')->where("order_sn = '{$result['order_sn']}'")->find();
                    
        $this->assign('order', $order);
        if($result['status'] == 1)
            $this->display('success');   
        else
            $this->display('error');   
    }


    //Paypal 支付成功 后操作

    public function notify() {
        // 由于这个文件只有被Paypal的服务器访问，所以无需考虑做什么页面什么的，
        // 这个页面不是给人看的，是给机器看的
        $order_id = (int) $_GET['orderid'];
        $order_info = D('Order')->getOrderDetail($order_id);

        // 由于该URL不仅仅只有Paypal的服务器能访问，其他任何服务器都可以向该方法发起请求。
        // 所以要判断请求发起的合法性，也就是要判断请求是否是paypal官方服务器发起的

        // 拼凑 post 请求数据
        $req = 'cmd=_notify-validate';// 验证请求
        foreach ($_POST as $k=>$v){
            $v = urlencode(stripslashes($v));
            $req .= "&{$k}={$v}";
        }

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,'http://www.paypal.com/cgi-bin/webscr');
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$req);
        $res = curl_exec($ch);
        curl_close($ch);

        if( $res && !empty($order_info) ) {
            // 本次请求是否由Paypal官方的服务器发出的请求
            if(strcmp($res, 'VERIFIED') == 0) {
                /**
                 * 判断订单的状态
                 * 判断订单的收款人
                 * 判断订单金额
                 * 判断货币类型
                 */
                if(($_POST['payment_status'] != 'Completed' && $_POST['payment_status'] != 'Pending')
                    OR ($_POST['receiver_email'] != $this->account)
                    OR ($_POST['mc_gross'] != 13)
                    OR ('USD' != $_POST['mc_currency'])) {
                    // 如果有任意一项成立，则终止执行。由于是给机器看的，所以不用考虑什么页面。直接输出即可
                    exit('fail');
                } else {// 如果验证通过，则证明本次请求是合法的
                    D('Order')->finishOrder($order_id);// 更改订单状态
                    exit('success');
                }
            } else {
                exit('fail');
            }
        }
    }


//    public function notify(){
//        $order_id=I('order_id');
//        $order=M('order')->where("order_id=$order_id")->find();
//        update_pay_status($order['order_sn']);
//    }

    //支付完成后跳转
    public function finish() {
        $this->success('The purchase is successful');
    }


}
